package authuserbc

// 前端 https(明文)  + 后端 bcrypt 加密存储
import (
	"time"

	"gitee.com/tgodfather/utility/auth"
	"github.com/golang-jwt/jwt/v5"
)

type JWTClaims struct {
	Username string `json:"username"`
	jwt.RegisteredClaims
}

type UserTokenManager struct {
	secretKey string
}

func (t *UserTokenManager) GenerateToken(username string, duration time.Duration, opts ...auth.TokenOption) (tokenstr string, err error) { // 产生token

	// opts := auth.NewTokenOptions(topts...)

	// Create claims with user information
	claims := &JWTClaims{
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(duration)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	// Generate token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	signedToken, err := token.SignedString([]byte(t.secretKey))
	if err != nil {
		return "", err
	}
	return signedToken, nil
}

func (t *UserTokenManager) VerifyToken(tokenString string, topts ...auth.TokenOption) (valid bool, user string, err error) { // 校验token
	// Parse and validate the token
	claims := &JWTClaims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return []byte(t.secretKey), nil
	})

	if err != nil || !token.Valid {
		return false, "", err
	}

	return true, claims.Username, nil

}

func NewUserTokenManager(opt ...auth.TokenOption) auth.AuthTokenManager {

	opts := auth.NewTokenOptions(opt...)

	return &UserTokenManager{
		secretKey: opts.SecretKey,
	}

}
